package service

import (
	"fmt"
	"goapp-web-server/app/models"
	"goapp-web-server/app/utils/orm"
)

type SysUserService interface {
	Login(username string, password string) (models.SysUser, error)
	GetAll() ([]models.SysUser, error)
	GetByID(id string) (models.SysUser, error)
}

func NewUserService() SysUserService {
	return new(userService)
}

type userService struct {
}

// login
func (s *userService) Login(username string, password string) (models.SysUser, error) {
	engine := orm.Engine
	user := models.SysUser{}
	_, err := engine.Table("sys_user").
		Select("sys_user.*, sys_user_info.*").
		Join("INNER", "sys_user_info", "sys_user_info.user_id = sys_user.id").
		Where("sys_user.deleted_at is NULL AND sys_user.user_name = ? AND sys_user.password = ?", username, password).
		Get(&user)
	if err != nil {
		fmt.Println("error:", err)
	}
	return user, nil
}

// user list
func (s *userService) GetAll() ([]models.SysUser, error) {
	engine := orm.Engine
	users := make([]models.SysUser, 0)
	err := engine.Table("sys_user").
		Select("sys_user.*, sys_user_info.*").
		Join("INNER", "sys_user_info", "sys_user_info.user_id = sys_user.id").
		Where("sys_user.deleted_at is NULL").
		Limit(10, 0).
		Find(&users)
	if err != nil {
		fmt.Println("error:", err)
		return nil, err
	}
	return users, nil
}

// get uesr by id
func (s *userService) GetByID(id string) (models.SysUser, error) {
	engine := orm.Engine
	user := models.SysUser{}
	_, err := engine.Table("sys_user").
		Select("sys_user.*, sys_user_info.*").
		Join("INNER", "sys_user_info", "sys_user_info.user_id = sys_user.id").
		Where("sys_user.deleted_at is NULL AND sys_user.id = ?", id).
		Get(&user)

	fmt.Println(user.UserName)
	if err != nil {
		fmt.Println("error:", err)
		return user, err
	}
	return user, nil
}
